package com.luoxue.execsql.rest.bean.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luoxue.execsql.common.util.ResultBody;
import com.luoxue.execsql.common.util.TableData;
import com.luoxue.execsql.rest.bean.base.service.IBaseService;
import com.luoxue.execsql.common.util.BaseEntity;
import com.luoxue.execsql.rest.entity.SysDataSource;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.List;

public abstract class BaseController<T extends BaseEntity, M extends BaseMapper<T>, S extends IBaseService<T, M>> {
    protected final S service;

    public BaseController(S service) {
        this.service = service;
    }

    @GetMapping
    protected Mono<ResultBody> list(T entity) {
        IPage<T> page = getTiPage(entity);
        return Mono.just(TableData.genResult(page));
    }

    protected IPage<T> getTiPage(T entity) {
        IPage<T> page = new Page<>();
        if (entity.getPageNum() != null) {
            page.setPages(entity.getPageNum());
        }
        if (entity.getPageSize() != null) {
            page.setSize(entity.getPageSize());
        }
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        this.queryParams(entity, queryWrapper);
        page = service.page(page, queryWrapper);
        page.setTotal(service.count(queryWrapper));
        return page;
    }

    protected abstract void queryParams(T entity, QueryWrapper<T> queryWrapper);


    @GetMapping("/{id}")
    public Mono<ResultBody> getById(@PathVariable String id) {
        return Mono.just(ResultBody.ok("查询成功", service.getById(id)));
    }

    @PostMapping
    public Mono<ResultBody> save(@RequestBody T entity) {
        return Mono.just(ResultBody.ok("添加成功", service.save(entity)));
    }

    @PutMapping
    public Mono<ResultBody> updateById(@RequestBody T entity) {
        return Mono.just(ResultBody.ok("修改成功", service.updateById(entity)));
    }

    @DeleteMapping("/{id}")
    public Mono<ResultBody> removeById(@PathVariable Long id) {
        return Mono.just(ResultBody.ok("删除成功", service.removeById(id)));
    }

    @DeleteMapping("/batch/{ids}")
    public Mono<ResultBody> removeByIds(@PathVariable List<Long> ids) {
        return Mono.just(ResultBody.ok("删除成功", service.removeByIds(ids)));
    }
}
